<?
/* check login data in db */
require_once './includes/db_connection.php';
echo("db connected<br>");

$user = $_POST['user'];
$pass = $_POST['pass'];

$sql_login = "SELECT * FROM user WHERE username=?";
$sql_lastlog = "UPDATE user SET lastlog_dt=NOW(), lastlog_ip=? WHERE userid=?";


/**
 * Update last login data
 * 
 * @param int $userid User ID
 */
function setlastlog($userid) {
	global $db, $sql_lastlog;
	try {
		$pslastlog = $db->prepare($sql_lastlog);
		$pslastlog->execute(array($_SERVER['REMOTE_ADDR'], $userid));
	} catch(Exception $e) {
		die("Chyba SQL [update last log]");
	}
}

/**
 * 
 *  BODY
 * 
 */
/* check empty user name field */
if($user == "") {
	header("Location: http://".$_SERVER["HTTP_HOST"]."/?err=5");
	exit();
}
echo("user not empty<br>");


try{
	/* load user data from db */
	$pslogin = $db->prepare($sql_login);
	$pslogin->execute(array($user));
	$userdata = $pslogin->fetch(PDO::FETCH_ASSOC);
	echo("user data loaded<br>");

	/* check user existence */
	if(empty($userdata['userid'])) {
		header("Location: http://".$_SERVER["HTTP_HOST"]."/?err=1");
		exit();
	}
	echo("login exist<br>");

	/* verify password */
	$pass_md5 = md5($pass);
	if($pass_md5 != $userdata['password']) {
		header("Location: http://".$_SERVER["HTTP_HOST"]."/?err=2");
		exit();
	}
	echo("password ok<br>");
	
	/* update last login info */
	setlastlog($userdata['userid']);	

	/* login ok, go to user page */
	session_start();
	header("Cache-control: private");
	$_SESSION['user_isLogged'] = 1;
	$_SESSION['user_name'] = $userdata['username'];
	$_SESSION['user_id'] = $userdata['userid'];
	$_SESSION['lastlog_dt'] = $userdata['lastlog_dt'];
	$_SESSION['lastlog_ip'] = $userdata['lastlog_ip'];
	header("Location: ./user.php");
	exit();
} catch (Exception $e) {
	die ("Chyba SQL [login]");
}
?>
